package com.tanhua.server.service;

import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.ContactVo;
import com.tanhua.model.vo.PageResultVo;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.exception.ErrorResult;
import com.tanhua.server.interceptor.UserHolderThreadLocal;
import com.tanhua.utils.Constants;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2021/12/4 23:41
 */
@Service
public class MessageService {


    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private FriendApi friendApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;



    /**
     * 根据环信id查询用户详细信息
     * @param huanxinId
     * @return
     */
    public UserInfoVo findUserInfoByHuanxin(String huanxinId) {
        // 1. 根据环信id查询user
        User user =  userApi.findByHuanxinId(huanxinId);
        // 2. 获取userId查询userInfo
        Long userId = user.getId();
        UserInfo userInfo = userInfoApi.findById(userId);
        // 3. 将userInfo数据封装到userInfoVo中
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        // 4. 判断userInfo中是否存在Integer的age，设置到UserInfo中的String的ag
        if(userInfo.getAge() != null){
            userInfoVo.setAge(userInfo.getAge().toString());
        }
        return userInfoVo;
    }

    /**
     * 添加好友
     * @param friendId
     */
    public void contacts(Long friendId) {

        // 1. 将好友关系注册到环信
        boolean aBoolean = huanXinTemplate.addContact(Constants.HX_USER_PREFIX + UserHolderThreadLocal.getId(),
                Constants.HX_USER_PREFIX + friendId);
        if (!aBoolean){
            throw new BusinessException(ErrorResult.error());
        }
        // 2. 如果注册成功，记录好友到mongodb
        friendApi.save(UserHolderThreadLocal.getId(), friendId);
    }


    /**
     * 删除好友
     * @param friendId
     */
    public void delete(Long friendId){

        // 将好友关系从环信删除
        boolean result = huanXinTemplate.removeContact(Constants.HX_USER_PREFIX + UserHolderThreadLocal.getId(),
                Constants.HX_USER_PREFIX + friendId);
        if(!result){
            throw new BusinessException(ErrorResult.error());
        }
        // 如果删除成功，就将好友从mongodb删除
        friendApi.remove(UserHolderThreadLocal.getId(), friendId);
    }

    /**
     * 分页查询联系人列表
     * @param page
     * @param pageSize
     * @param keyword
     * @return
     */
    public PageResultVo findFriends(Integer page, Integer pageSize, String keyword) {

        // 1. 调用api查询当前用户的好友数据List<Friend>
        List<Friend> friendList = friendApi.findByUserId(UserHolderThreadLocal.getId(), page, pageSize);
        if(CollectionUtil.isEmpty(friendList)){
            return new PageResultVo();
        }
        // 2. 使用hutool提取数据列表中的好友id
        List<Long> friendIds = CollectionUtil.getFieldValues(friendList, "friendId", Long.class);
        // 3. 调用userInfo查询好友的用户详情
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(keyword);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userInfo, friendIds);
        // 4. 构造vo对象
        List<ContactVo> vos = new ArrayList<>();
        for (Friend friend : friendList) {
            UserInfo userInfo1 = map.get(friend.getFriendId());
            if(userInfo1 != null){
                ContactVo contactVo = ContactVo.init(userInfo1);
                vos.add(contactVo);
            }
        }
        PageResultVo vo = new PageResultVo(page, pageSize, 0, vos);
        return vo;
    }
}
